import { ChangeEvent, FC, useState } from 'react'
import styles from './EditHeader.module.scss'
import { Button, Input, message, Space, Typography } from 'antd'
import { CheckOutlined, EditOutlined, LeftOutlined, LoadingOutlined } from '@ant-design/icons'
import { useNavigate, useParams } from 'react-router-dom'
import EditToolbar from './EditToolbar'
import useGetPageInfo from '../hooks/useGetPageInfo'
import { useDispatch } from 'react-redux'
import { pageInfoAction } from '../../../store/page-info-reducer'
import useGetComponentInfo from '../hooks/useGetComponentInfo'
import { useKeyPress, useRequest } from 'ahooks'
import { updateQuestionService } from '../../../services/question'

const TitleElem: FC = () => {
  const [editState, setEditState] = useState(false)
  const dispatch = useDispatch()
  const { title } = useGetPageInfo()

  function handleChangeTitle(e: ChangeEvent<HTMLInputElement>) {
    const newTitle = e.target.value.trim()
    if (!newTitle) return

    dispatch(pageInfoAction.changePageTitle(newTitle))
  }

  return (
    <Space>
      {!editState && <Typography.Title>{title}</Typography.Title>}
      {editState && (
        <Input
          value={title}
          onBlur={() => setEditState(false)}
          onPressEnter={() => setEditState(false)}
          onChange={handleChangeTitle}
        />
      )}
      <Button icon={<EditOutlined />} type="text" onClick={() => setEditState(true)} />
    </Space>
  )
}

const SaveButton: FC = () => {
  const { id } = useParams()
  useKeyPress(['meta.s', 'ctrl.s'], (e: KeyboardEvent) => {
    e.preventDefault()
    if (loading) return
    save()
  })
  const { componentList } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()

  const { run: save, loading } = useRequest(
    async () => {
      if (!id) return
      return await updateQuestionService(id, { componentList, ...pageInfo })
    },
    {
      manual: true,
    }
  )

  return (
    <Button onClick={save} disabled={loading} icon={loading ? <LoadingOutlined /> : <CheckOutlined />}>
      保存
    </Button>
  )
}

const PublishButton: FC = () => {
  const nav = useNavigate()
  const { id } = useParams()
  const { componentList } = useGetComponentInfo()
  const pageInfo = useGetPageInfo()

  const { run: pub, loading } = useRequest(
    async () => {
      if (!id) return
      return await updateQuestionService(id, { componentList, ...pageInfo, isPublished: true })
    },
    {
      manual: true,
      onSuccess: () => {
        message.success('发布成功')
        nav({ pathname: `/question/stat/${id}` })
      },
    }
  )

  return (
    <Button type="primary" onClick={pub} disabled={loading} icon={loading ? <LoadingOutlined /> : null}>
      发布
    </Button>
  )
}

const EditHeader: FC = () => {
  const nav = useNavigate()

  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button
              type="link"
              icon={<LeftOutlined />}
              onClick={() => {
                nav(-1)
              }}
            >
              返回
            </Button>
            <TitleElem />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolbar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  )
}

export default EditHeader
